package com.example.firstapp;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;

public class Music02Activity extends AppCompatActivity {
    Intent intent;
    static String song_path;
    private myConn conn;
    static MusicService.MyBinder binder;
    static ArrayList<String> songList = new ArrayList<>();
    static int state = 0;//0:暂停中 1:播放中
    static int index;
    ImageButton bt_m_left;
    @SuppressLint("StaticFieldLeak")
    static ImageButton bt_m_start;
    ImageButton bt_m_right;
    ImageButton bt_m_stop;
    @SuppressLint("StaticFieldLeak")
    static TextView tv_song_name;
    @SuppressLint("StaticFieldLeak")
    static TextView tv_time;
    @SuppressLint("StaticFieldLeak")
    static SeekBar seekBar;
    ImageView iv_play;
    static int playMod = 0;

    @SuppressLint({"StaticFieldLeak", "HandlerLeak"})
    public static Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            //处理消息
            Bundle bundle = msg.getData();
            //获取歌曲长度和当前播放位置，并设置到进度条上
            int duration = bundle.getInt("duration");
            int currentPosition = bundle.getInt("currentPosition");
            seekBar.setMax(duration);
            seekBar.setProgress(currentPosition);
            setTime(currentPosition);
            if (Math.abs(duration - currentPosition) < 600) {
                if(playMod==0){
                    index = (index + 1) % songList.size();
                    tactilePlayer();
                }else {
                    tactilePlayer();
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music02);

        //获取意图对象
        Intent intent01 = getIntent();
        songList = intent01.getStringArrayListExtra("songList");
        try {
            index = intent01.getIntExtra("index", -1);
            song_path = String.valueOf(songList.get(index));
        } catch (Exception ignored) {
            song_path = "";
        }

        //初始化播放服务
        conn = new myConn();
        intent = new Intent(Music02Activity.this, MusicService.class);
        bindService(intent, conn, BIND_AUTO_CREATE);

        //绑定组件
        bt_m_left = findViewById(R.id.bt_m_left);
        bt_m_start = findViewById(R.id.bt_m_start);
        bt_m_right = findViewById(R.id.bt_m_right);
        tv_song_name = findViewById(R.id.tv_song_name);
        bt_m_stop = findViewById(R.id.bt_m_stop);
        seekBar = findViewById(R.id.pb_song);
        tv_time = findViewById(R.id.tv_time);
        iv_play = findViewById(R.id.iv_play);

        tv_song_name.setSelected(true);

        //播放按钮监听
        bt_m_start.setOnClickListener(view -> {
            if (state == 0) {
                Log.i("music", "点击播放");
                startPlay();
            } else {
                Log.i("music", "点击暂停");
                if (binder.pause()) {
                    Log.i("music", "暂停成功");
                    state = 0;
                    bt_m_start.setImageResource(R.drawable.on);
                }
            }
        });

        //上一曲按钮监听
        bt_m_left.setOnClickListener(view -> {
            if (index == 0)
                index = songList.size() - 1;
            else
                index = index - 1;
            tactilePlayer();
        });

        //下一曲按钮监听
        bt_m_right.setOnClickListener(view -> {
            index = (index + 1) % songList.size();
            tactilePlayer();
        });

        //停止按钮监听
        bt_m_stop.setOnClickListener(view -> {
            binder.stopPlay();
            Log.i("music", "停止成功");
            state = 0;
            bt_m_start.setImageResource(R.drawable.on);
            seekBar.setProgress(0);
            setTime(0);
        });

        //绑定进度条
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (!binder.seekPlayProgress(seekBar.getProgress())) {
                    startPlay();
                    binder.seekPlayProgress(seekBar.getProgress());
                }
            }
        });

        //播放顺序图标监听
        iv_play.setOnClickListener(view -> {
            if (playMod == 0) {
                iv_play.setImageResource(R.drawable.one_circulation);
                playMod = 1;
            } else {
                iv_play.setImageResource(R.drawable.circulation);
                playMod = 0;
            }
        });
    }

    //开始播放
    private static void startPlay() {
        if (binder.play(song_path)) {
            Log.i("music", "播放成功");
            String[] tmp = song_path.split("/");
            String name = tmp[tmp.length - 1].split("\\.")[0];
            tv_song_name.setText(name);
            state = 1;
            bt_m_start.setImageResource(R.drawable.off);
        }
    }

    //切歌
    private static void tactilePlayer() {
        binder.stopPlay();
        Log.i("music", "播放停止");
        state = 0;
        bt_m_start.setImageResource(R.drawable.on);
        song_path = songList.get(index);
        startPlay();
    }

    private static class myConn implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            binder = (MusicService.MyBinder) service;
            startPlay();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    }

    //设置时间
    public static void setTime(int ms) {
        String HMSTime;
        ms /= 1000;
        int mint = (ms % 3600) / 60;
        int sed = ms % 60;
        String mintStr = String.valueOf(mint);
        if (mint < 10) {
            mintStr = "0" + mintStr;
        }
        String sedStr = String.valueOf(sed);
        if (sed < 10) {
            sedStr = "0" + sedStr;
        }
        HMSTime = mintStr + ":" + sedStr;
        tv_time.setText(HMSTime);
    }

    protected void onDestroy() {
        binder.stopPlay();
        unbindService(conn);
        super.onDestroy();
    }
}